<?php

/**
 * PRD = Produto
 * OUT = Fora
 */
class ZFPainel_Controller_Tela extends ZFPainel_Controller
{

    public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
    {
        parent::__construct($request, $response, $invokeArgs);
        //$acl = ZC_Painel_Acl::getInstance();
        //$acl->init();

        ZC_Plugin_Storage_Init::api_init();
    }

    public function indexAction()
    {
        $this->noRender();
    }

    public function pegarAction()
    {
        $this->testTela();

        $params = $this->_getAllParams();

        $strategyClassFile = $this->getControllerClassFile($params['strategyController']);
        if (!file_exists($strategyClassFile)) {
            die('StrategyClass inexistente');
        }

        include $strategyClassFile;

        $strategyAction = $params['strategyAction'];
        $strategyController = $params['strategyController'];

        $options = array();

        $strategyClass = $this->getControllerClassName($strategyController);
        $strategyObject = new $strategyClass();
        $strategyActionName = $this->getActionMethodName($strategyAction);
        if (method_exists($strategyObject, $strategyActionName)) {
            $strategyObject->$strategyActionName(array(
                'params' => $params,
                    ) + $options);
        }

        $this->setRender();
    }

    public function forbiddenAction()
    {
        $acl = ZC_Painel_Acl::getInstance();
        $this->view->msg = (null != ($msg = $acl->getForbiddenMsg())) ? $msg : 'Acesso negado';
    }

    private function getControllerClassFile($controller)
    {
        return $this->getFrontController()->getControllerDirectory($this->_getParam('module'))
                . '/' . ucfirst($controller) . 'TelaController.php';
    }

    private function getControllerClassName($controller)
    {
        return ucfirst($this->_getParam('module')) . '_' . ucfirst($controller) . 'TelaController';
    }

    private function getActionMethodName($action)
    {
        return $action . 'Action';
    }

    private function setRender()
    {
        $params = $this->_getAllParams();

        $this->_helper->viewRenderer->setRender($params['strategyController'] . '/' . $params['strategyAction']);
    }

    private function testTela()
    {
        $params = $this->_getAllParams();

        $fileScriptView = $this->getFrontController()->getModuleDirectory($params['module'])
                . '/views/scripts/tela/'
                . $params['strategyController']
                . '/' . $params['strategyAction']
                . '.phtml'
        ;

        if (!file_exists($fileScriptView)) {
            throw new Zend_Controller_Action_Exception('Tela inexistente', 404);
        }
    }

}
